package com.example.capsule_chat0322.listener;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.capsule_chat0322.activity.ChatActivity;
import com.example.capsule_chat0322.adapter.MsgAdapter;
import com.example.capsule_chat0322.bean.GlobalRoomBean;
import com.example.capsule_chat0322.bean.MessageBean;
import com.example.capsule_chat0322.bean.Msg;
import com.example.capsule_chat0322.bean.UserInfoBean;
import com.example.capsule_chat0322.configuration.Constant;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.global.GlobalChatRoomMap;
import com.example.capsule_chat0322.global.GlobalThreadPool;
import com.example.capsule_chat0322.global.LRUCache;
import com.example.capsule_chat0322.interfaces.NettyMessageInterface;
import com.example.capsule_chat0322.request.UserInfoRequest;

import java.util.Base64;
import java.util.List;


/**
 * @Author: zhuzhiming
 * @Date: 2022/4/27 20:15
 */
public class NettyGroupMessageListener implements NettyMessageInterface {

    private boolean hasCache = false;


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void consumerMessage(MessageBean messageBean) {


        GlobalRoomBean globalRoomBean = GlobalChatRoomMap.getRoomInfo(messageBean.getRoomName());
        if (globalRoomBean == null)
            return;

        ChatActivity activity = (ChatActivity) globalRoomBean.getActivity();

        if (messageBean.getMsgType() == 7 && messageBean.getSenderId() != null && messageBean.getSenderId().equals(GlobalAssistMap.getObject("userId")))
            return;

        if (messageBean.getMsgType() == 7) {
            doChangeRoomPeopleCount(activity, messageBean.getPeopleChangeCount());
            List<Msg> msgList = globalRoomBean.getMsgList();
            String str = messageBean.getPeopleChangeCount() + "|" + messageBean.getSenderName();
            Msg receiveMsg = new Msg(messageBean.getSenderId(), messageBean.getRoomName(), Msg.WORD_TYPE, str, Msg.TYPE_REMIND, "",false);
            updateMessageList(msgList, receiveMsg, globalRoomBean, activity, messageBean);
            return;
        }


        if (messageBean.getSenderId().equals(GlobalAssistMap.getObject("userId"))) {
            int msgId = messageBean.getLocalMsdId();
            Msg cacheMsg = (Msg) GlobalAssistMap.getObject(msgId + "msg");
            cacheMsg.setId(messageBean.getMsgId());
            GlobalAssistMap.removeObject(msgId + "msg");
            return;
        }


        MessageBean finalMessageBean = messageBean;

        String senderId = messageBean.getSenderId();
        final UserInfoBean[] userInfoBean = {(UserInfoBean) GlobalAssistMap.getObject(senderId + "Info")};
        if (userInfoBean[0] == null) {
            UserInfoRequest.doGetUserInfoRequest(new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(@NonNull Message message) {
                    userInfoBean[0] = (UserInfoBean) message.obj;
                    if (userInfoBean[0] != null) {
                        GlobalAssistMap.putObject(senderId + "Info", userInfoBean[0]);
                    }
                    return true;
                }
            }), senderId);
        }

        ChatActivity finalActivity = activity;
        GlobalThreadPool.buildThreadPool().execute(new Runnable() {
            @Override
            public void run() {

                finalActivity.runOnUiThread(new Runnable() {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void run() {
                        List<Msg> msgList = globalRoomBean.getMsgList();
                        final String[] senderAvatarPath = {(String) GlobalAssistMap.getObject(messageBean.getSenderId() + "Avatar")};
                        if ((senderAvatarPath[0] == null || senderAvatarPath[0].equals("")) && !messageBean.getSenderAvatarPath().contains("/")) {
                            senderAvatarPath[0] = messageBean.getSenderAvatarPath();
                            GlobalAssistMap.putObject((finalMessageBean.getSenderId() + "Avatar"), messageBean.getSenderAvatarPath());
                        }
                        if ((senderAvatarPath[0] == null || senderAvatarPath[0].equals("")) && messageBean.getSenderAvatarPath().contains("/")) {


                            LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                            Bitmap bitmap = (Bitmap) lruCache.get(messageBean.getSenderAvatarPath().substring(messageBean.getSenderAvatarPath().lastIndexOf("/")));
                            // Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(messageBean.getSenderAvatarPath().substring(messageBean.getSenderAvatarPath().lastIndexOf("/")));
                            if (bitmap == null) {
                                hasCache = false;
                                Handler handler = new Handler(new Handler.Callback() {
                                    @Override
                                    public boolean handleMessage(@NonNull Message message) {

                                        UserInfoBean userInfoBean = (UserInfoBean) message.obj;
                                        if (userInfoBean != null) {
                                            if (userInfoBean.getAvatarServerPath() != null && !userInfoBean.getAvatarServerPath().equals("")) {
                                                senderAvatarPath[0] = Constant.IMAGE_PATH + userInfoBean.getAvatarServerPath().substring(userInfoBean.getAvatarServerPath().lastIndexOf("/") + 1);
                                                Bitmap bitmap = BitmapFactory.decodeFile(senderAvatarPath[0]);
                                                if (bitmap == null) {
                                                    UserInfoRequest.getAvatar(new Handler(new Handler.Callback() {
                                                        @Override
                                                        public boolean handleMessage(@NonNull Message message) {
                                                            GlobalAssistMap.putObject(finalMessageBean.getSenderId() + "Avatar", senderAvatarPath[0]);
                                                            return true;
                                                        }
                                                    }), userInfoBean.getAvatarServerPath());
                                                }
                                            } else {
                                                senderAvatarPath[0] = userInfoBean.getAvatarUrl();
                                            }

                                            Msg receiveMsg = null;

                                            if (finalMessageBean.getMsgType() == Msg.WORD_TYPE) {
                                                receiveMsg = new Msg(finalMessageBean.getSenderId(), finalMessageBean.getRoomName(), Msg.WORD_TYPE, finalMessageBean.getContent(), Msg.TYPE_RECEIVE, senderAvatarPath[0],false);
                                                updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);
                                            } else {
                                                if (finalMessageBean.getMsgType() == 1) {

                                                    LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                                                    Bitmap bitmap = (Bitmap) lruCache.get(finalMessageBean.getFileName());
                                                    // Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(finalMessageBean.getFileName());
                                                    if (bitmap == null) {
                                                        byte[] by = Base64.getDecoder().decode(finalMessageBean.getContent());
                                                        bitmap = BitmapFactory.decodeByteArray(by, 0, by.length);
                                                        if (bitmap != null) {
                                                            lruCache.put(finalMessageBean.getFileName(), bitmap);
                                                            // GlobalAssistMap.putObject(finalMessageBean.getFileName(), bitmap);
                                                        }
                                                        by = null;
                                                    }
                                                    receiveMsg = new Msg(finalMessageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, finalMessageBean.getFileName(), finalMessageBean.getRoomName(), senderAvatarPath[0], null,false);
                                                    updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);
                                                } else if (finalMessageBean.getMsgType() == 2) {
                                                    receiveMsg = new Msg(finalMessageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, Constant.FILE_SERVER_PATH + messageBean.getFileName(), finalMessageBean.getRoomName(), senderAvatarPath[0], finalMessageBean.getFileName() + " "+finalMessageBean.getFileSize(),false);
                                                    updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);
                                                } else if (finalMessageBean.getMsgType() == 3) {

                                                    String cacheKey = finalMessageBean.getFileName();
                                                    LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                                                    Bitmap bitmap = (Bitmap) lruCache.get(cacheKey);
                                                    if (bitmap == null) {
                                                        byte[] by = Base64.getDecoder().decode(finalMessageBean.getContent());
                                                        bitmap = BitmapFactory.decodeByteArray(by, 0, by.length);
                                                        if (bitmap != null) {
                                                            lruCache.put(finalMessageBean.getFileName(), bitmap);
                                                            //GlobalAssistMap.putObject(finalMessageBean.getFileName(), bitmap);
                                                        }
                                                        by = null;
                                                    }

                                                    receiveMsg = new Msg(finalMessageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, Constant.VIDEO_SERVER_PATH + finalMessageBean.getFileName(), finalMessageBean.getRoomName(), senderAvatarPath[0], ".mp4 ",false);
                                                    updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);

                                                } else if (messageBean.getMsgType() == 8) {

                                                    int msgId = messageBean.getMsg().getId();
                                                    for (int i = 0; i < msgList.size(); i++) {
                                                        if (msgList.get(i).getId() == msgId) {
                                                            Msg newMsg = new Msg(finalMessageBean.getSenderId(), messageBean.getRoomName(), Msg.RECALL_TYPE, null, Msg.TYPE_RECEIVE, senderAvatarPath[0],false);
                                                            msgList.remove(i);
                                                            msgList.add(i, newMsg);
                                                            break;
                                                        }
                                                    }

                                                    String str = "" + "|" + messageBean.getSenderName();
                                                    Msg remindMsg = new Msg(messageBean.getSenderId(), messageBean.getRoomName(), Msg.WORD_TYPE, str, Msg.TYPE_REMIND, "",false);
                                                    updateMessageList(msgList, remindMsg, globalRoomBean, activity, messageBean);

                                                }
                                            }

                                        }
                                        return true;
                                    }
                                });

                                UserInfoRequest.doGetUserInfoRequest(handler, finalMessageBean.getSenderId());
                            } else {
                                hasCache = true;
                            }

                        } else if (hasCache || !messageBean.getSenderAvatarPath().contains("/") || (senderAvatarPath[0] != null && !senderAvatarPath[0].equals(""))) {
                            Msg receiveMsg = null;
                            String avatarPath = hasCache ? (String) GlobalAssistMap.getObject(messageBean.getSenderAvatarPath().substring(messageBean.getSenderAvatarPath().lastIndexOf("/"))) : ((senderAvatarPath[0] == null || senderAvatarPath[0].equals("")) ? messageBean.getSenderAvatarPath() : senderAvatarPath[0]);
                            if (finalMessageBean.getMsgType() == Msg.WORD_TYPE) {
                                receiveMsg = new Msg(finalMessageBean.getSenderId(), finalMessageBean.getRoomName(), Msg.WORD_TYPE, finalMessageBean.getContent(), Msg.TYPE_RECEIVE, avatarPath,false);
                                updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);
                            } else {

                                if (finalMessageBean.getMsgType() == 1) {
                                    LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                                    Bitmap bitmap = (Bitmap) lruCache.get(finalMessageBean.getFileName());
                                    // Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(finalMessageBean.getFileName());
                                    if (bitmap == null) {
                                        byte[] by = Base64.getDecoder().decode(finalMessageBean.getContent());
                                        bitmap = BitmapFactory.decodeByteArray(by, 0, by.length);
                                        if (bitmap != null) {
                                            lruCache.put(finalMessageBean.getFileName(), bitmap);
                                            // GlobalAssistMap.putObject(finalMessageBean.getFileName(), bitmap);
                                        }
                                        by = null;
                                    }
                                    receiveMsg = new Msg(finalMessageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, finalMessageBean.getFileName(), finalMessageBean.getRoomName(), avatarPath, null,false);
                                    updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);
                                } else if (finalMessageBean.getMsgType() == 2) {
                                    receiveMsg = new Msg(finalMessageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, messageBean.getFilePath(), finalMessageBean.getRoomName(), avatarPath, finalMessageBean.getFileName() + " " + finalMessageBean.getFileSize(),false);
                                    updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);
                                } else if (finalMessageBean.getMsgType() == 3) {
                                    LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                                    String cacheKey = finalMessageBean.getFileName();
                                    Bitmap bitmap = (Bitmap) lruCache.get(cacheKey);
                                    //Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(cacheKey);
                                    if (bitmap == null) {
                                        byte[] by = Base64.getDecoder().decode(finalMessageBean.getContent());
                                        bitmap = BitmapFactory.decodeByteArray(by, 0, by.length);
                                        if (bitmap != null) {
                                            lruCache.put(finalMessageBean.getFileName(), bitmap);
                                            // GlobalAssistMap.putObject(finalMessageBean.getFileName(), bitmap);
                                        }
                                        by = null;
                                    }

                                    receiveMsg = new Msg(finalMessageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, Constant.VIDEO_SERVER_PATH + finalMessageBean.getFileName(), finalMessageBean.getRoomName(), senderAvatarPath[0], ".mp4 ",false);
                                    updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);

                                } else if (messageBean.getMsgType() == 8) {

                                    int msgId = messageBean.getMsg().getId();
                                    for (int i = 0; i < msgList.size(); i++) {
                                        if (msgList.get(i).getId() == msgId) {
                                            Msg newMsg = new Msg(finalMessageBean.getSenderId(), messageBean.getRoomName(), Msg.RECALL_TYPE, null, Msg.TYPE_RECEIVE, senderAvatarPath[0],false);
                                            msgList.remove(i);
                                            msgList.add(i, newMsg);
                                            break;
                                        }
                                    }

                                    String str = "" + "|" + messageBean.getSenderName();
                                    Msg remindMsg = new Msg(messageBean.getSenderId(), messageBean.getRoomName(), Msg.WORD_TYPE, str, Msg.TYPE_REMIND, "",false);
                                    updateMessageList(msgList, remindMsg, globalRoomBean, activity, messageBean);

                                }

                            }

                        }
                    }
                });
            }
        });

    }


    private void updateMessageList(List<Msg> msgList, Msg receiveMsg, GlobalRoomBean globalRoomBean, Activity activity, MessageBean finalMessageBean) {
        receiveMsg.setId(finalMessageBean.getMsgId());
        msgList.add(receiveMsg);
        globalRoomBean.setMsgList(msgList);
        MsgAdapter adapter = new MsgAdapter(msgList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        RecyclerView msgRecyclerView = globalRoomBean.getMsgRecyclerView();
        msgRecyclerView.setLayoutManager(layoutManager);
        msgRecyclerView.setAdapter(adapter);
        adapter.notifyItemInserted(msgList.size() - 1);//当有新消息是刷新RecyclerView中的显示
        msgRecyclerView.scrollToPosition(msgList.size() - 1);//将RecyclerView定位在最后一行
        globalRoomBean.setActivity(activity);
        globalRoomBean.setRoomName(finalMessageBean.getRoomName());
        globalRoomBean.setMsgRecyclerView(msgRecyclerView);
        globalRoomBean.setMsgList(msgList);
        globalRoomBean.setAdapter(adapter);
        GlobalChatRoomMap.putRoomInfo(finalMessageBean.getRoomName(), globalRoomBean);
    }

    @Override
    public void dealInactive() {
    }

    private void doChangeRoomPeopleCount(ChatActivity activity, int count) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                activity.updatePeopleCount(count);
            }
        });

    }
}
